package com.aizhixin.lab.course.template.service;

import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.config.Config;
import com.aizhixin.lab.course.template.domain.ImportResultDomain;
import com.aizhixin.lab.course.template.dto.ImportAssistDTO;
import com.aizhixin.lab.course.template.dto.ImportChapterDTO;
import com.aizhixin.lab.course.template.dto.ImportChapterFileDTO;
import com.aizhixin.lab.course.template.entity.TemplateAssist;
import com.aizhixin.lab.course.template.entity.TemplateChapter;
import com.aizhixin.lab.course.template.entity.TemplateChapterFile;
import com.aizhixin.lab.course.template.repository.TemplateAssistRepository;
import com.aizhixin.lab.course.template.repository.TemplateChapterFileRepository;
import com.aizhixin.lab.course.template.repository.TemplateChapterRepository;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@Transactional
public class TemplateImportService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private TemplateImportZipService importZipService;
    @Lazy
    @Autowired
    private TemplateChapterService chapterService;
    @Autowired
    private TemplateChapterRepository chapterRepository;
    @Autowired
    private TemplateChapterFileRepository chapterFileRepository;
    @Autowired
    private TemplateAssistRepository assistRepository;
    @Autowired
    private Config config;
    private static final String KEY_PREFIX = "import:template:";

    @Async
    public void importData(Long userId, Long templateId, String fileName, File file) {
        setImportResult(userId, templateId, 10, null);
        try {
            if (!fileName.endsWith("zip")) {
                setImportResult(userId, templateId, 30, "传入文件格式错误");
                return;
            }
            Map<String, List> map = importZipService.getImportData(file);
            if (map.get("chapterDTOS") != null && map.get("chapterDTOS").size() > 0) {
                deleteAllChapter(templateId);
                importChapter(templateId, null, map.get("chapterDTOS"));
                chapterService.updateTemplateChapterCount(templateId);
            }
            if (map.get("assistDTOS") != null && map.get("assistDTOS").size() > 0) {
                deleteAllAssist(templateId);
                importAssist(templateId, null, map.get("assistDTOS"));
            }
            setImportResult(userId, templateId, 20, null);
        } catch (RuntimeException e) {
            log.warn("RuntimeException", e);
            setImportResult(userId, templateId, 30, e.getMessage());
            throw e;
        } finally {
            file.delete();
        }
    }

    private void deleteAllChapter(Long templateId) {
        List<TemplateChapter> list = chapterRepository.findByTemplateId(templateId);
        if (list != null && !list.isEmpty()) {
            Set<Long> ids = new HashSet<>();
            for (TemplateChapter item : list) {
                ids.add(item.getId());
            }
            chapterFileRepository.deleteByChapterIdIn(ids);
        }
        chapterRepository.deleteByTemplateId(templateId);
    }

    private void deleteAllAssist(Long templateId) {
        assistRepository.deleteByTemplateId(templateId);
    }

    private void importChapter(Long templateId, Long parentId, List<ImportChapterDTO> chapterDTOS) {
        if (chapterDTOS != null && !chapterDTOS.isEmpty()) {
            for (ImportChapterDTO dto : chapterDTOS) {
                TemplateChapter chapter = null;// chapterRepository.findByTemplateIdAndChapterNoAndDeleteFlag(templateId, dto.getChapterNo(), DataValidity.VALID.getState());
                if (chapter == null) {
                    chapter = new TemplateChapter();
                    chapter.setTemplateId(templateId);
                    chapter.setParentId(parentId);
                    chapter.setChapterNo(dto.getChapterNo());
                    chapter.setType(dto.getType());
                    chapter.setIsExp(false);
                    String no = chapter.getChapterNo().replaceAll("\\.", "");
                    chapter.setOrderNo(Integer.parseInt(no));
                }
                chapter.setName(dto.getName());
                chapter = chapterRepository.save(chapter);
                if (dto.getChapterDTOS() != null && !dto.getChapterDTOS().isEmpty()) {
                    importChapter(templateId, chapter.getId(), dto.getChapterDTOS());
                }
                if (dto.getFileDTOS() != null && !dto.getFileDTOS().isEmpty()) {
                    List<TemplateChapterFile> addFiles = new ArrayList<>();
                    for (ImportChapterFileDTO fileDTO : dto.getFileDTOS()) {
                        TemplateChapterFile file = null;//chapterFileRepository.findByChapterIdAndNameAndDeleteFlag(chapter.getId(), fileDTO.getName(), DataValidity.VALID.getState());
                        if (file == null) {
                            file = new TemplateChapterFile();
                            file.setChapterId(chapter.getId());
                            file.setName(fileDTO.getName());
                            file.setType(fileDTO.getType());
                            file.setNo(fileDTO.getNo());
                            file.setFileKey(fileDTO.getFileKey());
                            file.setFileUrl(fileDTO.getFileUrl());
                            addFiles.add(file);
                        }
                    }
                    chapterFileRepository.save(addFiles);
                }
            }
        }
    }

    private void importAssist(Long templateId, Long parentId, List<ImportAssistDTO> assistDTOS) {
        if (assistDTOS != null && !assistDTOS.isEmpty()) {
            for (ImportAssistDTO item : assistDTOS) {
                List<TemplateAssist> assists = null;// assistRepository.findByTemplateIdAndName(templateId, item.getName());
                TemplateAssist assist = null;
                if (assists != null && !assists.isEmpty()) {
                    assist = assists.get(0);
                } else {
                    assist = new TemplateAssist();
                    assist.setTemplateId(templateId);
                    assist.setParentId(parentId);
                    assist.setIsDir(item.getIsDir());
                    assist.setName(item.getName());
                    assist.setFileKey(item.getFileKey());
                    assist.setFileUrl(item.getFileUrl());
                    assist = assistRepository.save(assist);
                }
                if (item.getChildren() != null && !item.getChildren().isEmpty()) {
                    importAssist(templateId, assist.getId(), item.getChildren());
                }
            }
        }
    }

    private ImportResultDomain setImportResult(Long userId, Long templateId, int state, String message) {
        ImportResultDomain d = new ImportResultDomain();
        d.setState(state);
        d.setMessage(message);
        redisTemplate.opsForValue().set(KEY_PREFIX + userId + templateId, JSON.toJSONString(d), 1, TimeUnit.HOURS);
        return d;
    }

    public ImportResultDomain importResult(Long userId, Long templateId) {
        String json = redisTemplate.opsForValue().get(KEY_PREFIX + userId + templateId);
        return JSON.parseObject(json, ImportResultDomain.class);
    }
}
